<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 充电桩列表 -->
      <el-col :span="12" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="clearfix">
              <span>充电桩管理</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="primary"
                icon="Plus"
                @click="handleAddCharger"
                >新增充电桩</el-button
              >
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="chargerList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column label="序号" width="50" type="index" />
            <el-table-column
              label="充电桩编号"
              align="center"
              prop="sn"
              width="220"
              :show-overflow-tooltip="true"
            />

            <el-table-column
              label="枪口数量"
              align="center"
              prop="gunNum"
            />
            <el-table-column
              label="服务器IP"
              align="center"
              prop="serverIp"
            />
            <el-table-column
              label="服务器端口"
              align="center"
              prop="serverPort"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleUpdate(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleSelectCharger(scope.row)"
                  >查看详情</el-button
                >
                              <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleConnect(scope.row)"
                  >上电</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleDisconnect(scope.row)"
                  >下电</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>

      <!-- 充电枪列表 -->
      <el-col :span="12" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="clearfix">
              <span>充电枪管理</span>
              <span v-if="selectedCharger" style="margin-left: 10px; color: #409EFF; font-size: 14px;">
                (当前充电桩: {{ selectedCharger.sn }})
              </span>
              <el-button
                style="float: right; padding: 3px 0"
                type="primary"
                icon="Plus"
                :disabled="!selectedCharger"
                @click="handleAddChargerGun"
                >新增充电枪</el-button
              >
            </div>
          </template>

          <el-table
            v-loading="gunLoading"
            :data="chargerGunList"
            @selection-change="handleGunSelectionChange"
          >
            <el-table-column label="序号" width="50" type="index" />
            <el-table-column
              label="枪口号"
              align="center"
              prop="number"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="状态"
              align="center"
              prop="isInsert"
              :formatter="gunStatusFormatter"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  link
                  :disabled="scope.row.isInsert === 1"
                  @click="handleInsertGun(scope.row)"
                  >插枪</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  link
                  :disabled="scope.row.isInsert === 0"
                  @click="handleRemoveGun(scope.row)"
                  >拔枪</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleDeleteGun(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="gunTotal > 0"
            :total="gunTotal"
            v-model:page="gunQueryParams.pageNum"
            v-model:limit="gunQueryParams.pageSize"
            @pagination="getGunList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改充电桩对话框 -->
    <el-dialog
      :title="chargerTitle"
      v-model="openCharger"
      width="500px"
      append-to-body
    >
      <el-form ref="chargerRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="充电桩编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入充电桩编号" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-select v-model="form.brand" placeholder="请选择品牌">
            <el-option label="云快充" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="直流" :value="0" />
            <el-option label="交流" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="枪口数量" prop="gunNum">
          <el-input-number
            v-model="form.gunNum"
            controls-position="right"
            :min="1"
            :disabled="form.id !== undefined"
          />
        </el-form-item>
        <el-form-item label="服务器IP" prop="serverIp">
          <el-input v-model="form.serverIp" placeholder="请输入服务器IP" />
        </el-form-item>
        <el-form-item label="服务器端口" prop="serverPort">
          <el-input
            v-model="form.serverPort"
            placeholder="请输入服务器端口"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitChargerForm">确 定</el-button>
          <el-button @click="cancelCharger">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改充电枪对话框 -->
    <el-dialog
      :title="chargerGunTitle"
      v-model="openChargerGun"
      width="500px"
      append-to-body
    >
      <el-form
        ref="chargerGunRef"
        :model="gunForm"
        :rules="gunRules"
        label-width="100px"
      >
        <el-form-item label="枪口号" prop="number">
          <el-input v-model="gunForm.number" placeholder="请输入枪口号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitChargerGunForm">确 定</el-button>
          <el-button @click="cancelChargerGun">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, watch, getCurrentInstance } from 'vue'
import {
  listCharger,
  getCharger,
  delCharger,
  addCharger,
  updateCharger,
  connectCharger,
  disconnectCharger
} from '@/api/charge/charger'
import {
  listChargerGun,
  getChargerGun,
  delChargerGun,
  addChargerGun,
  updateChargerGun,
  insertGun,
  removeGun
} from '@/api/charge/chargerGun'
import { ElMessageBox, ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()

const chargerList = ref([])
const chargerGunList = ref([])
const openCharger = ref(false)
const openChargerGun = ref(false)
const loading = ref(true)
const gunLoading = ref(true)
const total = ref(0)
const gunTotal = ref(0)
const ids = ref([])
const gunIds = ref([])
const chargerTitle = ref("")
const chargerGunTitle = ref("")
const selectedCharger = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sn: undefined,
    brand: undefined
  },
  gunForm: {},
  gunQueryParams: {
    pageNum: 1,
    pageSize: 10,
    chargerId: undefined
  },
  rules: {
    sn: [{ required: true, message: "充电桩编号不能为空", trigger: "blur" }],
    brand: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
    type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
    gunNum: [{ required: true, message: "枪口数量不能为空", trigger: "blur" }],
    serverIp: [{ required: true, message: "服务器IP不能为空", trigger: "blur" }],
    serverPort: [
      { required: true, message: "服务器端口不能为空", trigger: "blur" }
    ]
  },
  gunRules: {
    number: [{ required: true, message: "枪口号不能为空", trigger: "blur" }]
  }
})

const {
  form,
  queryParams,
  gunForm,
  gunQueryParams,
  rules,
  gunRules
} = toRefs(data)

/** 查询充电桩列表 */
function getList() {
  console.log('调用getList获取充电桩列表，参数：', queryParams.value)
  loading.value = true
  listCharger(queryParams.value)
    .then(response => {
      
      // 响应拦截器已经处理了数据，直接返回{list: [...], total: "1"}格式
      if (response && response.list) {
        console.log('使用list格式')
        chargerList.value = response.list
        total.value = parseInt(response.total) || 0
      } else if (Array.isArray(response)) {
        console.log('使用数组格式')
        chargerList.value = response
        total.value = response.length
      } else if (response && response.rows) {
        console.log('使用rows格式')
        chargerList.value = response.rows
        total.value = response.total
      } else {
        console.log('没有匹配的数据格式，清空列表')
        chargerList.value = []
        total.value = 0
      }
      console.log('最终chargerList值：', chargerList.value)
      console.log('最终total值：', total.value)
      loading.value = false
    })
    .catch(error => {
      console.error('获取充电桩列表失败：', error)
      loading.value = false
    })
}

// 页面初始化时调用getList()，并在充电桩列表加载完成后自动选中第一个充电桩
onMounted(() => {
  getList()
})

// 监听充电桩列表变化，自动选中第一个充电桩
watch(chargerList, (newList) => {
  if (newList && newList.length > 0 && !selectedCharger.value) {
    selectedCharger.value = newList[0]
    getGunList()
  }
})

/** 查询充电枪列表 */
function getGunList() {
  if (!selectedCharger.value) return
  
  console.log('调用getGunList获取充电枪列表，参数：', gunQueryParams.value)
  gunLoading.value = true
  gunQueryParams.value.chargerId = selectedCharger.value.id
  listChargerGun(gunQueryParams.value)
    .then(response => {
      console.log('充电枪列表响应数据原始结构：', response)
      console.log('响应数据类型：', typeof response)
      console.log('是否有list属性：', response && response.list)
      console.log('list类型：', response.list && typeof response.list)
      console.log('total类型：', response.total && typeof response.total)
      
      // 响应拦截器已经处理了数据，直接返回{list: [...], total: "1"}格式
      if (response && response.list) {
        console.log('使用list格式')
        chargerGunList.value = response.list
        gunTotal.value = parseInt(response.total) || 0
      } else if (Array.isArray(response)) {
        console.log('使用数组格式')
        chargerGunList.value = response
        gunTotal.value = response.length
      } else if (response && response.rows) {
        console.log('使用rows格式')
        chargerGunList.value = response.rows
        gunTotal.value = response.total
      } else {
        console.log('没有匹配的数据格式，清空列表')
        chargerGunList.value = []
        gunTotal.value = 0
      }
      console.log('最终chargerGunList值：', chargerGunList.value)
      console.log('最终gunTotal值：', gunTotal.value)
      gunLoading.value = false
    })
    .catch(error => {
      console.error('获取充电枪列表失败：', error)
      gunLoading.value = false
    })
}

/** 充电枪状态格式化 */
function gunStatusFormatter(row, column, cellValue) {
  return cellValue === 1 ? '已插枪' : '未插枪'
}

/** 品牌格式化 */
function brandFormatter(row, column, cellValue) {
  return cellValue == 1 ? '云快充' : cellValue
}

/** 类型格式化 */
function typeFormatter(row, column, cellValue) {
  return cellValue == 0 ? '直流' : cellValue == 1 ? '交流' : cellValue
}

/** 取消按钮 */
function cancelCharger() {
  openCharger.value = false
  resetCharger()
}

/** 取消按钮 */
function cancelChargerGun() {
  openChargerGun.value = false
  resetChargerGun()
}

/** 表单重置 */
function resetCharger() {
  form.value = {
    id: undefined,
    sn: undefined,
    brand: undefined,
    type: undefined,
    gunNum: 1,
    serverIp: undefined,
    serverPort: undefined
  }
  if (proxy.$refs && proxy.$refs.chargerRef) {
    proxy.$refs.chargerRef.resetFields()
  }
}

/** 表单重置 */
function resetChargerGun() {
  gunForm.value = {
    id: undefined,
    number: undefined,
    chargerId: selectedCharger.value ? selectedCharger.value.id : undefined
  }
  if (proxy.$refs && proxy.$refs.chargerGunRef) {
    proxy.$refs.chargerGunRef.resetFields()
  }
}

/** 新增按钮操作 */
function handleAddCharger() {
  resetCharger()
  chargerTitle.value = "添加充电桩"
  openCharger.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log('点击编辑按钮，行数据：', row)
  resetCharger()
  const id = row.id
  console.log('准备获取充电桩详情，ID：', id)
  getCharger(id).then(response => {
    console.log('获取充电桩详情响应：', response)
    if (response) {
      form.value = response
      chargerTitle.value = "修改充电桩"
      openCharger.value = true
    } else {
      ElMessage({ message: "获取充电桩详情失败", type: "error" })
      console.error('获取充电桩详情响应为空：', response)
    }
  }).catch(error => {
    ElMessage({ message: "获取充电桩详情失败", type: "error" })
    console.error('获取充电桩详情失败：', error)
  })
}

/** 提交按钮 */
function submitChargerForm() {
  proxy.$refs["chargerRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        updateCharger(form.value).then(response => {
          ElMessage({ message: "修改成功", type: "success" })
          openCharger.value = false
          // 只有在修改当前选中的充电桩时才需要刷新列表
          if (selectedCharger.value && selectedCharger.value.id === form.value.id) {
            getList()
          }
        })
      } else {
        addCharger(form.value).then(response => {
          ElMessage({ message: "新增成功", type: "success" })
          openCharger.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value
  ElMessageBox.confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delCharger(ids)
  }).then(() => {
    // 如果删除的是当前选中的充电桩，清空选中状态
    if (selectedCharger.value && selectedCharger.value.id === row.id) {
      selectedCharger.value = null
      chargerGunList.value = []
    }
    getList()
    ElMessage({ message: "删除成功", type: "success" })
  }).catch(() => {})
}

/** 上电操作 */
function handleConnect(row) {
  connectCharger(row.id).then(response => {
    ElMessage({ message: "上电操作已发送", type: "success" })
    // 重新获取充电枪列表以更新状态
    getGunList()
  })
}

/** 下电操作 */
function handleDisconnect(row) {
  disconnectCharger(row.id).then(response => {
    ElMessage({ message: "下电操作已发送", type: "success" })
    // 重新获取充电枪列表以更新状态
    getGunList()
  })
}

/** 选择充电桩 */
function handleSelectCharger(row) {
  selectedCharger.value = row
  getGunList()
}

/** 新增充电枪 */
function handleAddChargerGun() {
  resetChargerGun()
  chargerGunTitle.value = "添加充电枪"
  openChargerGun.value = true
}

/** 提交充电枪表单 */
function submitChargerGunForm() {
  proxy.$refs["chargerGunRef"].validate(valid => {
    if (valid) {
      gunForm.value.chargerId = selectedCharger.value.id
      if (gunForm.value.id) {
        updateChargerGun(gunForm.value).then(response => {
          ElMessage({ message: "修改成功", type: "success" })
          openChargerGun.value = false
          getGunList()
        })
      } else {
        addChargerGun(gunForm.value).then(response => {
          ElMessage({ message: "新增成功", type: "success" })
          openChargerGun.value = false
          getGunList()
        })
      }
    }
  })
}

/** 删除充电枪 */
function handleDeleteGun(row) {
  const ids = row.id || gunIds.value
  ElMessageBox.confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delChargerGun(ids)
  }).then(() => {
    getGunList()
    ElMessage({ message: "删除成功", type: "success" })
  }).catch(() => {})
}

/** 插枪操作 */
function handleInsertGun(row) {
  insertGun(selectedCharger.value.id, row.id).then(response => {
    ElMessage({ message: "插枪操作已发送", type: "success" })
    getGunList()
  })
}

/** 拔枪操作 */
function handleRemoveGun(row) {
  removeGun(selectedCharger.value.id, row.id).then(response => {
    ElMessage({ message: "拔枪操作已发送", type: "success" })
    getGunList()
  })
}

</script>